package me.zhengjie.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.service.FlywayService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * Flyway 数据库迁移控制器
 * 
 * @author zhengjie
 * @date 2024-01-01
 */
@Api(tags = "数据库迁移管理")
@RestController
@RequestMapping("/api/flyway")
@RequiredArgsConstructor
public class FlywayController {

    private final FlywayService flywayService;

    @ApiOperation("执行数据库迁移")
    @PostMapping("/migrate")
    @PreAuthorize("@el.check('flyway:manage')")
    public ResponseEntity<String> migrate() {
        try {
            flywayService.migrate();
            return ResponseEntity.ok("数据库迁移执行成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("数据库迁移失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取迁移信息")
    @GetMapping("/info")
    @PreAuthorize("@el.check('flyway:view')")
    public ResponseEntity<String> getMigrationInfo() {
        try {
            String info = flywayService.getMigrationInfo();
            return ResponseEntity.ok(info);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取迁移信息失败: " + e.getMessage());
        }
    }

    @ApiOperation("验证迁移脚本")
    @PostMapping("/validate")
    @PreAuthorize("@el.check('flyway:manage')")
    public ResponseEntity<String> validate() {
        try {
            flywayService.validate();
            return ResponseEntity.ok("迁移脚本验证通过");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("迁移脚本验证失败: " + e.getMessage());
        }
    }

    @ApiOperation("清理数据库（仅开发环境）")
    @PostMapping("/clean")
    @PreAuthorize("@el.check('flyway:manage')")
    public ResponseEntity<String> clean() {
        try {
            flywayService.clean();
            return ResponseEntity.ok("数据库清理完成");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("数据库清理失败: " + e.getMessage());
        }
    }
} 